<?php

Class Database
{
    private function Database()
    {
    $databaseName = $GLOBALS['configuration']['db'];
	$driver = $GLOBALS['configuration']['pdoDriver'];
	$serverName = $GLOBALS['configuration']['host'];
	$databaseUser = $GLOBALS['configuration']['user'];
	$databasePassword = $GLOBALS['configuration']['pass'];
	$databasePort = $GLOBALS['configuration']['port'];
	if (!isset($this->connexion))
	{
            $this->connexion = new PDO($driver.':host='.$serverName.';port='.$databasePort.';dbname='.$databaseName, $databaseUser, $databasePassword);
            $this->connexion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	}
	if (!$this->connexion)
	{
            throw new Exception('I cannot connect to the database. Please edit configuration.php with your database configuration.');
	}
    }

    public static function Connect()
    {
	static $database = null;
	if (!isset($database))
	{
            $database = new Database();
	}
	return $database->connexion;
    }

    public static function Reader($query, $connexion)
    {
	try
	{
            $result = $connexion->Query($query);
	}
	catch(PDOException $e)
	{
            return false;
	}
        return $result;
    }

    public static function Read($result)
    {
	try
	{
            return $result->fetch();
	}
	catch (PDOException $e)
	{
            return false;
	}
    }

    public static function NonQuery($query, $connexion)
    {
	try
	{
            $r = $connexion->query($query);
            if ($r === false)
            {
		return 0;
            }
            return $r->rowCount();
	}
	catch (PDOException $e)
	{
            return false;
	}
    }

    public static function Query($query, $connexion)
    {
	try
	{
            $i = 0;
            $r = $connexion->query($query);
            foreach ($r as $row)
            {
            	$i++;
            }
            return  $i;
	}
	catch (PDOException $e)
	{
            return false;
	}
    }

    public static function InsertOrUpdate($query, $connexion)
    {
	try
	{
            $r = $connexion->query($query);
            return $connexion->lastInsertId();
	}
	catch (PDOException $e)
	{
            return false;
	}
    }
}

?>